const M=require("ming_node")
const fs=require("fs");

if(!global.CONFIG.watchFile){
    return;
}


sseApp=M.sseServer()
app.get("/sseServer",sseApp)


M.getFileDirList = function (path) {
    //遍历读取文件
    function readFile(path, filesList, targetObj) {
        files = fs.readdirSync(path);//需要用到同步读取
        files.forEach(walk);
        function walk(file) {
            states = fs.statSync(path + '/' + file);
            if (states.isDirectory()) {
                var item;
                let dir=path + '/' + file;
                if(dir.indexOf("lib")==-1){
                    dirList.push(path + '/' + file)
                }
                if (targetObj["children"]) {
                    item = {name: file, children: [], value: path + '/' + file};
                    targetObj["children"].push(item);
                } else {
                    item = {name: file, children: [], value: path + '/' + file};
                    filesList.push(item);
                }
                readFile(path + '/' + file, filesList, item);
            }
        }
    }
    var dirList=[]
    var filesList = [];
    var targetObj = {};
    readFile(path, filesList, targetObj);
    return dirList;
}






M.watch=function (watch) {
    let t1=new Date().getTime();
    let t2=new Date().getTime();
    fs.watch(watch, (event, file) => {
        if (file) {
            //console.log(event,"=======>event")
            if(event==="change"){
                t2=new Date().getTime();
                if(t2-t1>800){
                    t1=t2;
                    if(file.indexOf(".")>0){
                        console.log("change "+file);
                        sseApp.send("change");
                    }
                }
            }else if(event==="rename"){
                insertImportJs="";
                //console.log("rename "+file)
               // sseApp.send("rename")
            }
        }
    });
}


let r= M.getFileDirList("static")

r.forEach(u=>M.watch(u))
console.log("watch on ",r)